package com.cxf.lock;

import lombok.extern.log4j.Log4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @author xuanfei_Chen
 * @date 2020/4/5 5:53 下午
 */
@Log4j
public class LockTest implements Runnable{

    // 同时并发的线程数
    private static final int NUM = 10;
    // 按照线程数初始化倒计数器
    private static CountDownLatch cdl = new CountDownLatch(NUM);
    //private ZookeeperLockV1 lock = new ZookeeperLockV1();
    private ZookeeperLockV2 lock = new ZookeeperLockV2();
    @Override
    public void run() {
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        createOrder();
    }

    public static void main(String[] args) {
        for (int i = 1; i <= NUM; i++) {
            // 按照线程数迭代实例化线程
            new Thread(new LockTest()).start();
            // 创建一个线程，倒计数器减1
            cdl.countDown();
        }
    }

    //模拟创建订单
    private String createOrder(){
        String orderCode = null;
        lock.lock();
        try {
            orderCode = getOrderCode();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        //获取订单编号创建订单，省略业务代码
        log.warn(Thread.currentThread().getName() + "-" +orderCode);
        return orderCode;
    }

    //模拟订单自增长序列
    private static int i = 0;
    private String getOrderCode(){
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-");
        return sdf.format(now) + ++i;
    }
}
